package com.stylefeng.guns.modular.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.common.constant.state.ManagerStatus;
import com.stylefeng.guns.core.datascope.DataScope;
import com.stylefeng.guns.core.node.ZTreeNode;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.system.dao.UserMapper;
import com.stylefeng.guns.modular.system.model.User;
import com.stylefeng.guns.modular.system.service.IDeptService;
import com.stylefeng.guns.modular.system.service.IUserService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-02-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IDeptService deptService;

    @Autowired
    private WxCpService wxCpService;


    @Override
    public int setStatus(Integer userId, int status) {
        return this.baseMapper.setStatus(userId, status);
    }

    @Override
    public int changePwd(Integer userId, String pwd) {
        return this.baseMapper.changePwd(userId, pwd);
    }

    @Override
    public List<Map<String, Object>> selectUsers(DataScope dataScope, String name, String beginTime, String endTime, Integer deptid) {
        return this.baseMapper.selectUsers(dataScope, name, beginTime, endTime, deptid);
    }

    @Override
    public List<ZTreeNode> tree(Integer deptId){
        return this.baseMapper.tree(deptId);
    }

    @Override
    public int setRoles(Integer userId, String roleIds) {
        return this.baseMapper.setRoles(userId, roleIds);
    }

    @Override
    public User getByAccount(String account) {
        return this.baseMapper.getByAccount(account);
    }

    @Override
    @Transactional
    public void syncWxUser() throws WxErrorException {
        List<WxCpDepart> wxCpDepartList = deptService.syscWxDept();

        List<String> wxUserIdList = new ArrayList<>();
        for (WxCpDepart depart : wxCpDepartList) {
            List<WxCpUser> wxCpUsers = wxCpService.getUserService().listSimpleByDepartment(depart.getId(), false, 0);
            for (WxCpUser wxCpUser : wxCpUsers) {
                wxUserIdList.add(wxCpUser.getUserId());
                syncWxUser(wxCpUser);
            }
        }
        super.baseMapper.setOutOfUserDeleted(wxUserIdList);
    }

    private void syncWxUser(WxCpUser wxCpUser) {
        User user = new User();
        User oldUser = this.baseMapper.getByWxUserId(wxCpUser.getUserId());
        //如果用户未同步
        if (oldUser == null || oldUser.getStatus() == ManagerStatus.DELETED.getCode() ) {
            user.setAccount(wxCpUser.getUserId());
            user.setRoleid("6");
            user.setStatus(1);
            user.setPassword("111111");
            user.setSalt(ShiroKit.getRandomSalt(5));
            user.setPassword(ShiroKit.md5(user.getPassword(), user.getSalt()));
            user.setCreatetime(new Date());

        }else if(oldUser !=null){ //已同步
            user.setId(oldUser.getId());
            user.setRoleid(oldUser.getRoleid());
        }

        if (null != wxCpUser.getStatus() && wxCpUser.getStatus() == 2) {
            user.setStatus(ManagerStatus.FREEZED.getCode());
        }else{
            user.setStatus(ManagerStatus.OK.getCode());
        }
        user.setWxUserId(wxCpUser.getUserId());
        user.setName(wxCpUser.getName());
        user.setDeptid(wxCpUser.getDepartIds()[0]);
        if (null != wxCpUser.getGender()) {
            user.setSex(Integer.valueOf(wxCpUser.getGender().getCode()));
        }else{
            user.setSex(1);
        }
        insertOrUpdate(user);
    }

    @Override
    public void syncWxUser(String wxUserId,String neWxUserId) throws WxErrorException {
        WxCpUser wxCpUser = wxCpService.getUserService().getById(wxUserId);
        if (StringUtils.isNotEmpty(neWxUserId)) {
            wxCpUser.setUserId(neWxUserId);
        }
        syncWxUser(wxCpUser);
    }

    @Override
    public User getByWxUserId(String wxUserId){
        return super.baseMapper.getByWxUserId(wxUserId);
    }

}
